package com.etop.bank.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.etop.BankCard.BankCardAPI;
import com.etop.BankCard.BankCardInfoAPI;
import com.etop.bank.model.OcrKeyDatas;
import com.etop.bank.utils.BankConfig;
import com.etop.bank.utils.PhotoFromPhotoAlbum;
import com.etop.bank.view.OcrProgressDialog;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BankRecogActivity extends Activity {

	private BankCardAPI bankApi;
	private BankCardInfoAPI cardinfoapi;
	private OcrProgressDialog progress;
	private int IMPORT_PHOTO = 105;
	private int screenWidth;
	private int screenHeight;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		screenWidth = getWindowManager().getDefaultDisplay().getWidth();
		screenHeight = getWindowManager().getDefaultDisplay().getHeight();

		bankApi = BankCardAPI.getBankInstance();
		int initKernalCode = bankApi.initBankKernal(this);
		if (initKernalCode == 0) {
			if (cardinfoapi == null) {
				cardinfoapi = new BankCardInfoAPI();
				cardinfoapi.InitCardInfo();
			}
			String endTime = bankApi.GetEndTime();
			Log.e("BankScanActivity", "授权截止日期 ------------- " + endTime);

			Intent selectIntent = new Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
			selectIntent.setType("image/*");
			if (selectIntent.resolveActivity(getPackageManager()) != null) {
				startActivityForResult(selectIntent, IMPORT_PHOTO);
			}
		} else {
			LinearLayout linearLayout = new LinearLayout(this);
			setContentView(linearLayout);
			TextView mTvTishi = new TextView(this);
			mTvTishi.setText("OCR核心激活失败:" + initKernalCode + "\r\n错误信息：" + BankConfig.getErrorInfo(initKernalCode));
			mTvTishi.setTextColor(Color.BLACK);
			linearLayout.addView(mTvTishi);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null && requestCode == IMPORT_PHOTO) {
			//拿到选择的图片
			final String imageFilePath = PhotoFromPhotoAlbum.getRealPathFromUri(this, data.getData());
			if (!TextUtils.isEmpty(imageFilePath)) {
				progress = new OcrProgressDialog(BankRecogActivity.this);
				progress.show();
				new Thread(new Runnable() {
					@Override
					public void run() {
						//创建存银行卡号的数组
						char[] recogval = new char[30];
						//创建存银行卡其他信息的数组
						String[] cardinfo = new String[4];
						Bitmap bitmap = getSmallBitmap(imageFilePath, screenWidth, screenHeight);
						//调用识别接口
//                        final int recogCode = bankApi.ScanImage(imageFilePath, recogval);
						final int recogCode = bankApi.ScanBitmapImage(bitmap, recogval);
						Log.e("recogCode:", recogCode + "");
						if (recogCode == 0) {
							//获取识别结果
							cardinfoapi.GetCardInfo(recogval, cardinfo);
							//获取银行卡号
							String str = String.valueOf(recogval);
							String regEx = "[^0-9]";
							Pattern p = Pattern.compile(regEx);
							Matcher m = p.matcher(str);
							String bankNumber = m.replaceAll("").trim();
							//获取银行名称
							String bankName = cardinfo[0];
							//获取银行代码
							String bankCode = cardinfo[1];
							//获取卡名称
							String cardName = cardinfo[2];
							//获取卡类型
							String cardType = cardinfo[3];
//            Log.e("识别成功", "bankNumber:" + bankNumber + ",bankName:" + bankName + ",bankCode:" + bankCode
//                    + ",cardName:" + cardName + ",cardType:" + cardType);
							HashMap<String, String> hashMap = new HashMap<>();
							//将识别完成后，获取识别结果，添加到集合中
							hashMap.put(OcrKeyDatas.BANK_KEY[0], bankNumber);
							hashMap.put(OcrKeyDatas.BANK_KEY[1], bankName);
							hashMap.put(OcrKeyDatas.BANK_KEY[2], cardName);
							hashMap.put(OcrKeyDatas.BANK_KEY[3], bankCode);
							hashMap.put(OcrKeyDatas.BANK_KEY[4], cardType);

							Intent intent = new Intent();
							intent.putExtra(OcrKeyDatas.RECOG_CODE, recogCode);
							intent.putExtra(OcrKeyDatas.RECOG_RESULT_HASHMAP, hashMap);
							intent.putExtra(OcrKeyDatas.IMAGE_PATH, imageFilePath);
							BankRecogActivity.this.setResult(RESULT_OK, intent);
							BankRecogActivity.this.finish();
						} else {
							HashMap<String, String> hashMap = new HashMap<>();
							//将识别完成后，获取识别结果，添加到集合中
							hashMap.put(OcrKeyDatas.OCR_ERROR, "图像不清晰或图像中未发现银行卡-code:" + recogCode);
							Intent intent = new Intent();
							intent.putExtra(OcrKeyDatas.RECOG_CODE, recogCode);
							intent.putExtra(OcrKeyDatas.RECOG_RESULT_HASHMAP, hashMap);
							intent.putExtra(OcrKeyDatas.IMAGE_PATH, imageFilePath);
							BankRecogActivity.this.setResult(RESULT_OK, intent);
							BankRecogActivity.this.finish();
						}
						progress.dismiss();

					}
				}).start();
			}
		} else {
			finish();
		}
	}

	public Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		//避免出现内存溢出的情况，进行相应的属性设置。
		options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		options.inDither = true;

		return BitmapFactory.decodeFile(filePath, options);
	}

	/**
	 * <li> 计算图片的缩放值 </li>
	 *
	 * @param options   options
	 * @param reqWidth  宽
	 * @param reqHeight 高
	 * @return inSampleSize
	 */
	public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			final int heightRatio = Math.round((float) height / (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		return inSampleSize;
	}

	@Override
	protected void onDestroy() {
		bankApi.releaseKernal();
		super.onDestroy();

	}
}
